/**
 * 案例：通过AST的操作，完成前后端一体化
 */

const fs = require('fs');
const path = require('path');
const acorn = require('acorn');
const { print } = require('recast');
// 读取源文件
const srcFilePath = path.join(__dirname, './src/bus.js');
const outFilePath = path.join(__dirname, './dist/bus.js');
const srcFileContent = fs.readFileSync(srcFilePath, 'utf-8');
const originAST = acorn.parse(srcFileContent, {
    ecmaVersion: 'latest',
    sourceType: 'module',
});
// 读取所有 import @api 的语句
const allImportApiNode = originAST.body.filter((node, i) => {
    if (node.type === 'ImportDeclaration') {
        if (node.source.value.indexOf('@api') !== -1) {
            originAST.body[i].__index = i;
            return true;
        }
    }
    return false;
});
const apiValDeclarations = allImportApiNode.map((node) => {
    const apiName = node.specifiers[0].local.name;
    const apiPath = node.source.value.replace('@api', '/api');
    return {
        "type": "VariableDeclaration",
        "declarations": [
            {
                "type": "VariableDeclarator",
                "id": {
                    "type": "Identifier",
                    "name": apiName
                },
                "init": {
                    "type": "CallExpression",
                    "start": 16,
                    "end": 36,
                    "callee": {
                        "type": "Identifier",
                        "start": 16,
                        "end": 23,
                        "name": "request"
                    },
                    "arguments": [
                        {
                            "type": "Literal",
                            "start": 24,
                            "end": 35,
                            "value": apiPath,
                            "raw": `"${apiPath}"`
                        }
                    ],
                    "optional": false
                }
            }
        ],
        "kind": "const"
    };
});
// 删除源码中的 import @api 语句
let checkoutRmIndex = 0;
allImportApiNode.forEach((node) => {
    originAST.body.splice(node.__index - checkoutRmIndex, 1);
    checkoutRmIndex++;
});

// 在文件顶部追加团队的工具包
originAST.body.unshift({
    "type": "ImportDeclaration",
    "specifiers": [
        {
            "type": "ImportDefaultSpecifier",
            "local": {
                "type": "Identifier",
                "name": "request"
            }
        }
    ],
    "source": {
        "type": "Literal",
        "value": "@group/request",
        "raw": "\"@group/request\""
    }
});

// 把 request() 语句插入到所有 import 的语句后面
let lastImportIndex = 0;
originAST.body.some((node, i) => {
    if( node.type === 'ImportDeclaration' ) {
        lastImportIndex++;
        return false;
    }
    return true;
});

apiValDeclarations.forEach((node) => {
    originAST.body.splice(lastImportIndex, 0, node);
});

const outputConent = `// 狮子工具生成 \n ${print(originAST).code}`;
fs.writeFileSync(outFilePath, outputConent);





















































































/*
const fs = require('fs');
const path = require('path');
const acorn = require('acorn');
const { print } = require('recast');

// 读取源配置文件
const srcFilePath = path.join(__dirname, 'src/bus.js');
const srcFileContent = fs.readFileSync(srcFilePath, 'utf-8');
const outputFilePath = path.join(__dirname, 'dist/bus.js');
const originAST = acorn.parse(srcFileContent, {
    ecmaVersion: 'latest',
    sourceType: 'module',
});
// 获取所有import api节点
const allImportApiNode = originAST.body.filter((obj, i) => {
    if (obj.type === 'ImportDeclaration') {
        if (obj.source.value.indexOf('@api') !== -1) {
            originAST.body[i].__index = i;
            return true;
        }
    }
    return false;
});
// 生成 api节点的转换代码
const apiValDeclarations = allImportApiNode.map((node) => {
    const apiName = node.specifiers[0].local.name;
    const apiPath = node.source.value.replace('@api', '/api');
    return {
        "type": "VariableDeclaration",
        "declarations": [
            {
                "type": "VariableDeclarator",
                "id": {
                    "type": "Identifier",
                    "name": apiName,
                },
                "init": {
                    "type": "CallExpression",
                    "callee": {
                        "type": "Identifier",
                        "name": "request"
                    },
                    "arguments": [
                        {
                            "type": "Literal",
                            "value": apiPath,
                            "raw": `'${apiPath}'`
                        }
                    ],
                    "optional": false
                }
            }
        ],
        "kind": "const"
    };
});
// 删除所有import api节点
let checkRmIndex = 0;
allImportApiNode.forEach((node) => {
    originAST.body.splice(node.__index - checkRmIndex, 1);
    checkRmIndex++;
});
// 在顶部追加一个工具包
originAST.body.unshift({
    "type": "ImportDeclaration",
    "specifiers": [
      {
        "type": "ImportDefaultSpecifier",
        "local": {
          "type": "Identifier",
          "name": "request"
        }
      }
    ],
    "source": {
      "type": "Literal",
      "value": "@group/request",
      "raw": "'@group/request'"
    }
});
let lastImportIndex = 0;
originAST.body.some((node, i) => {
    if (node.type === 'ImportDeclaration') {
        lastImportIndex++;
        return false;
    }
    return true;
});
// 在import后追加生成api的节点
apiValDeclarations.forEach((apiValNode) => {
    originAST.body.splice(lastImportIndex, 0, apiValNode);
});

const outputConent = `// 本代码由工程脚本修改完成 \n ${print(originAST).code}`;
fs.writeFileSync(outputFilePath, outputConent);


*/

// originAST.body.forEach((node) => {
//     rmAllPois(node);
// });
// function rmAllPois(astNode){
//     astNode && Object.keys(astNode).forEach((key) => {
//         if(key === 'start' || key === 'end'){
//             delete astNode[key];
//         }else if(Array.isArray(astNode[key])){
//             astNode[key].forEach((item) => {
//                 rmAllPois(item);
//             });
//         }else if(astNode && typeof astNode[key] === 'object'){
//             rmAllPois(astNode[key]);
//         }
//     });
// }